/*
 * Copyright 2022 Rich yang, 18158898020@189.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <stdio.h>

int main(int argc, char *argv[])
{
	if (argc < 3) {
		fprintf(stderr, "Usage: %s binary hexdump\n", argv[0]);
		return -1;
	}

	FILE *input;
	FILE *output;
	int c, count;
	unsigned char buf[4];

	input = fopen(argv[1], "rb");
	if (input == NULL) {
		fprintf(stderr, "%s can not open\n", argv[1]);
		return -1;
	}
	output = fopen(argv[2], "w");
	if (output == NULL) {
		fprintf(stderr, "%s can not create\n", argv[2]);
		fclose(input);
		return -2;
	}
	count = 0;
	while ((c = getc(input)) != EOF) {
		buf[count%4] = c;
		if ((count+1)%4 == 0)
			fprintf(output, "%02X%02X%02X%02X\n", buf[3], buf[2], buf[1], buf[0]);
		count++;
	}

	fclose(input);
	fclose(output);
	printf("%d bytes write\n", count);
	return 0;
}
